package com.example.servlet.personalServlet;

import com.example.entity.Student;
import com.example.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet("/personal")
public class PersonalInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String currentStudentId = (String) session.getAttribute("studentId");

        if (currentStudentId == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();

            String sql = "SELECT * FROM student WHERE student_id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, currentStudentId);

            rs = stmt.executeQuery();
            if (rs.next()) {
                Student student = new Student(
                        rs.getString("student_id"),
                        rs.getString("name"),
                        rs.getString("grade"),
                        rs.getString("classes"),
                        rs.getString("email")
                );
                request.setAttribute("student", student);
            }

            String message = (String) session.getAttribute("message");
            String messageType = (String) session.getAttribute("messageType");
            if (message != null) {
                request.setAttribute("message", message);
                request.setAttribute("messageType", messageType);
                session.removeAttribute("message");
                session.removeAttribute("messageType");
            }

            request.getRequestDispatcher("personal.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", "获取用户信息失败：" + e.getMessage());
            request.setAttribute("messageType", "error");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }
}